package com.dny.asmtop.op;

import com.dny.asmtop.ASMMethodUtils;
import com.dny.asmtop.Command;
import com.dny.asmtop.MethodContext;
import jdk.internal.org.objectweb.asm.Type;

import java.util.Objects;

import static jdk.internal.org.objectweb.asm.Type.getType;

/**
 * Created by jlutt on 2018-01-16.
 * 类型转换cast
 * @author jlutt
 */
public class CommandCast implements Command {

  public static final Type THIS_TYPE = getType(Object.class);

  private final Command expression;
  private final Type targetType;

  public CommandCast(Command expression, Type type) {
    this.expression = expression;
    this.targetType = type;
  }

  @Override
  public Type type(MethodContext context) {
    return targetType == THIS_TYPE ? context.getThisType() : targetType;
  }

  @Override
  public Type generator(MethodContext context) {
    Type targetType = type(context);
    ASMMethodUtils.generatorAndCast(context, expression, targetType);
    return targetType;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CommandCast that = (CommandCast) o;
    return Objects.equals(expression, that.expression) &&
        Objects.equals(targetType, that.targetType);
  }

  @Override
  public int hashCode() {
    return Objects.hash(expression, targetType);
  }
}
